﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Templates_ActionPlan_Create : LoggedInPageBase
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        listSections.SelectedIndexChanged += new EventHandler(listSections_SelectedIndexChanged);
        listSections.DataBound += new EventHandler(listSections_DataBound);
        dsSections.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsSections_Select);

        dsCategories.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsCategories_Select);
        listCategories.ItemDataBound += new EventHandler<ListViewItemEventArgs>(listCategories_ItemDataBound);
    }

    void listSections_DataBound(object sender, EventArgs e)
    {
        var newPredicted = PendingCommitements.Sum(x => x.AveSavingPerMonth);
        var factory = new CarbonExchange.Bll.FootprintSavingFactory();
        var currentPredicted = factory.GetCurrentPotentialSaving(User.Identity.User.Id);
        var totalSaving = newPredicted + currentPredicted;
        //var oustanding = UserSections.Sum(x => x.Footprint) - predicted;
        //lblOutstandingCO2.Text = oustanding.ToString("0.## kg CO<sub>2</sub>e");
        lblPredictedSaving.Text = totalSaving.ToString("#,##0 kg CO<sub>2</sub>e");

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataBind();
        }
    }

    public override void DataBind()
    {
        var tmpAudit = LatestAudit;
        if (tmpAudit != null)
        {
            pnlActionPlan.Visible = true;
            pnlNoAudit.Visible = false;

            lblAuditDate.Text = string.Format("{0:dd MMMM yyyy} / {1:dd MMMM yyyy}", tmpAudit.StartDate, tmpAudit.EndDate);

            var tmpUserSections = UserSections;
            if (tmpUserSections != null)
            {
                var tmpFootprint = tmpUserSections.Sum(x => x.Footprint);

                //removed cost
                //lblAuditPrediction.Text = string.Format("{0:#,##0 kg} / {1:c}", tmpFootprint, ConvertToCurrency(tmpFootprint));
                lblAuditPrediction.Text = string.Format("{0:#,##0 kg}", tmpFootprint);
            }
        }
        else
        {
            pnlActionPlan.Visible = false;
            pnlNoAudit.Visible = true;
            lnkActionPlan.NavigateUrl = AcmsContext.ResolveUrl("~/MyCO2/CreateAudit.aspx", this);
        }
        base.DataBind();
    }

    private List<CarbonExchange.Bll.UserSection> _UserSections;
    protected List<CarbonExchange.Bll.UserSection> UserSections
    {
        get
        {
            if (LatestAudit != null && _UserSections == null)
            {
                var factory = new CarbonExchange.Bll.UserSectionFactory();
                _UserSections = factory.GetAllByAuditId(LatestAudit.Id);
            }
            return _UserSections;
        }
    }

    private CarbonExchange.Bll.Audit _LatestAudit;
    protected CarbonExchange.Bll.Audit LatestAudit
    {
        get
        {
            if (_LatestAudit == null)
            {
                var factory = new CarbonExchange.Bll.AuditFactory();
                _LatestAudit = factory.GetLatestCompletedByUserId(User.Identity.User.Id);
            }
            return _LatestAudit;
        }
    }

    protected void slider_ValueChanged(object sender, EventArgs e)
    {
        var catId = (int)listCategories.SelectedDataKey["Id"];
        var listPledges = listCategories.Items[listCategories.SelectedIndex].FindControl("listPledges") as ListView;
        if (listPledges != null)
        {
            CarbonExchange.Bll.Pledge.SolutionTypes? solutionType = null;
            if (slider.Value == 0)
            {
                solutionType = CarbonExchange.Bll.Pledge.SolutionTypes.Technolgical;
            }
            else if (slider.Value == 2)
            {
                solutionType = CarbonExchange.Bll.Pledge.SolutionTypes.Behavioural;
            }

            CarbonExchange.Bll.PledgeFactory factory = new CarbonExchange.Bll.PledgeFactory();
            listPledges.DataSource = factory.GetAllByCategoryIdAndType(catId, solutionType);
            listPledges.DataBind();
        }
    }

    protected void listPledges_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item is ListViewDataItem)
        {
            var pledge = ((ListViewDataItem)e.Item).DataItem as CarbonExchange.Bll.Pledge;
            var lblPledgeName = e.Item.FindControl("lblPledgeName") as Label;
            if (pledge != null && lblPledgeName != null)
            {
                CustomProperties[lblPledgeName.ClientID] = new CustomProperty() { Recommendation = pledge.Recommendation, Saving = pledge.AveSavingPerMonth };
                /*//ToDo:Fix Bug due to being databound twice
                try
                {
                    Page.ClientScript.RegisterExpandoAttribute(lblPledgeName.ClientID, "recommendation", pledge.Recommendation);
                    Page.ClientScript.RegisterExpandoAttribute(lblPledgeName.ClientID, "saving", pledge.AveSavingPerMonth.ToString("#.## kg"));
                }
                catch (ArgumentException)
                {
                }*/
            }
        }

    }

    void listCategories_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item is ListViewDataItem && ((ListViewDataItem)e.Item).DataItemIndex == ((ListView)sender).SelectedIndex)
        {
            var tmp = ((ListViewDataItem)e.Item).DataItem as CarbonExchange.Bll.PledgeCategory;
            var listPledges = e.Item.FindControl("listPledges") as ListView;
            if (tmp != null && listPledges != null)
            {
                CarbonExchange.Bll.Pledge.SolutionTypes? solutionType = null;
                if (slider.Value == 0)
                {
                    solutionType = CarbonExchange.Bll.Pledge.SolutionTypes.Technolgical;
                }
                else if (slider.Value == 2)
                {
                    solutionType = CarbonExchange.Bll.Pledge.SolutionTypes.Behavioural;
                }

                CustomProperties.Clear();
                CarbonExchange.Bll.PledgeFactory factory = new CarbonExchange.Bll.PledgeFactory();
                listPledges.DataSource = factory.GetAllByCategoryIdAndType(tmp.Id, solutionType).ToList();
                listPledges.DataBind();
            }
        }
    }

    void listSections_SelectedIndexChanged(object sender, EventArgs e)
    {
        listCategories.SelectedIndex = 0;
        listCategories.DataBind();
    }

    void dsCategories_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        int sectionId = (int)listSections.SelectedDataKey["Id"];
        CarbonExchange.Bll.PledgeCategoryFactory factory = new CarbonExchange.Bll.PledgeCategoryFactory();
        e.SetData(factory.GetAllBySectionId(sectionId));
    }

    void dsSections_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        CarbonExchange.Bll.SectionFactory factory = new CarbonExchange.Bll.SectionFactory();
        e.SetData(factory.GetAll());
    }


    private List<CarbonExchange.Bll.Commitment> _PendingCommitements;
    protected List<CarbonExchange.Bll.Commitment> PendingCommitements
    {
        get
        {
            if (_PendingCommitements == null)
            {
                var factory = new CarbonExchange.Bll.CommitmentFactory();
                _PendingCommitements = factory.GetAllPendingByUserId(User.Identity.User.Id).ToList();
            }
            return _PendingCommitements;
        }
    }

    protected void listPending_DataBinding(object sender, EventArgs e)
    {
        ListView listPending = sender as ListView;
        var item = listPending.NamingContainer as ListViewDataItem;
        var list = item.NamingContainer as ListView;
        var id = (int)list.DataKeys[item.DisplayIndex]["Id"];

        listPending.DataSource = PendingCommitements.Where(x => x.SectionId == id).ToList();
        
    }

    private List<CarbonExchange.Bll.Commitment> _AllCommitements;
    protected List<CarbonExchange.Bll.Commitment> AllCommitements
    {
        get
        {
            if (_AllCommitements == null)
            {
                var factory = new CarbonExchange.Bll.CommitmentFactory();
                _AllCommitements = factory.GetAllByUserId(User.Identity.User.Id).ToList();
            }
            return _AllCommitements;
        }
    }

    protected void cboPledge_DataBinding(object sender, EventArgs e)
    {
        var cboPledge = sender as CheckBox;
        var item = cboPledge.NamingContainer as ListViewDataItem;
        var pledge = item.DataItem as CarbonExchange.Bll.Pledge;
        var commitment = AllCommitements.Where(x => x.PledgeId == pledge.Id).SingleOrDefault();
        if (commitment != null && commitment.CommitmentDate != null)
        {
            cboPledge.Enabled = false;
            cboPledge.Checked = true;
        }
        else if (commitment != null && commitment.CommitmentDate == null)
        {
            cboPledge.Enabled = true;
            cboPledge.Checked = true;
        }
        else
        {
            cboPledge.Enabled = true;
            cboPledge.Checked = false;
        }
    }

    protected void cboPledge_CheckChanged(object sender, EventArgs e)
    {
        var cboPledge = sender as CheckBox;
        var item = cboPledge.NamingContainer as ListViewDataItem;
        var listView = item.NamingContainer as ListView;

        int pledgeId = (int)listView.DataKeys[item.DisplayIndex]["Id"];
        var factory = new CarbonExchange.Bll.CommitmentFactory();
        if (cboPledge.Checked)
        {
            PendingCommitements.Add(new CarbonExchange.Bll.Commitment(User.Identity.User.Id, pledgeId));
            factory.Save(PendingCommitements.Last());
        }
        else
        {
            var commitment = PendingCommitements.Where(x => x.PledgeId == pledgeId).SingleOrDefault();
            if (commitment != null)
            {
                factory.Delete(commitment);
                PendingCommitements.Remove(commitment);
            }
        }
        listSections.DataBind();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            var factory = new CarbonExchange.Bll.CommitmentFactory();
            var tmp = factory.GetAllPendingByUserId(User.Identity.User.Id).ToList();
            factory.CreateCommitments(tmp);
            AcmsContext.RedirectToUrl("~/MyCO2/MyCommitments.aspx", this);

        }
    }

    [Serializable]
    internal class CustomProperty
    {
        internal string Recommendation { get; set; }
        internal decimal Saving { get; set; }
    }

    private Dictionary<string, CustomProperty> CustomProperties = new Dictionary<string,CustomProperty>();

    protected override void OnPreRenderComplete(EventArgs e)
    {
        foreach (string key in CustomProperties.Keys)
        {
            Page.ClientScript.RegisterExpandoAttribute(key, "recommendation", CustomProperties[key].Recommendation);
            Page.ClientScript.RegisterExpandoAttribute(key, "saving", CustomProperties[key].Saving.ToString("0.## kg CO<sub>2</sub>e"));
        }
        base.OnPreRenderComplete(e);
    }

    protected override object SaveViewState()
    {
        ViewState["CustomProperties"] = CustomProperties;
        return base.SaveViewState();
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        CustomProperties = ViewState["CustomProperties"] as Dictionary<string, CustomProperty>;
    }
}
